package top.gokzzz.common.constant;

import org.apache.commons.lang3.LocaleUtils;

import java.util.Locale;

public enum Language {

    ZH_HANT("zh_TW", "繁體中文", true),
    ZH_HANS("zh_CN", "简体中文", false),
    PT("pt", "Português", false),
    EN("en", "English", false);

    private String code;
    private String displayName;
    private Locale locale;
    private boolean isDefault;

    private Language(String code, String displayName, boolean isDefault) {
        this.code = code;
        this.displayName = displayName;
        this.locale = LocaleUtils.toLocale(code);
        this.isDefault = isDefault;
    }

    public String getCode() {
        return code;
    }

    public String getDisplayName() {
        return displayName;
    }

    public Locale getLocale() {
        return locale;
    }

    public boolean isDefault() {
        return isDefault;
    }

    public static Language getDefault() {
        for (Language language : values()) {
            if (language.isDefault) {
                return language;
            }
        }
        throw new IllegalStateException("No default language specified");
    }

    public static Language findByCode(String code) {
        if (code != null) {
            for (Language language : values()) {
                if (language.getCode().equalsIgnoreCase(code)) {
                    return language;
                }
            }
        }
        return getDefault();
    }

    public static Locale getLocale(String value) {
        if (value != null) {
            for (Language language : values()) {
                if (language.getLocale().toString().equalsIgnoreCase(value)) {
                    return language.getLocale();
                }
            }
        }
        return getDefault().getLocale();
    }

    public static Locale[] getLocales() {
        Locale[] locales = new Locale[values().length];
        for (int i = 0; i < values().length; i++) {
            locales[i] = values()[i].getLocale();
        }
        return locales;
    }
}
